package com.xjj.sso.server.filter.impl;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.xjj.framework.XJJConstants;
import com.xjj.framework.spring.SpringBeanLoader;
import com.xjj.framework.utils.EncryptUtils;
import com.xjj.sso.project.cache.ProjectCache;
import com.xjj.sso.project.entity.ProjectEntity;
import com.xjj.sso.server.SSOConstants;
import com.xjj.sso.server.cache.TicketCache;
import com.xjj.sso.server.filter.SSOHandler;
import com.xjj.sso.server.filter.SSOHandlerSupport;
import com.xjj.sso.server.pojo.SSOIdentity;
import com.xjj.sso.server.pojo.User;
import com.xjj.sso.server.ticket.GrantingTicket;
import com.xjj.sso.server.ticket.ServiceTicket;
import com.xjj.sso.server.util.JsonUtil;
import com.xjj.sso.server.util.SSOUtils;
import com.xjj.sso.server.validation.UserAuthService;


public class SSOJsonpHandler extends SSOHandlerSupport implements SSOHandler{
	private static SSOJsonpHandler ssoHandler = new SSOJsonpHandler();
	public static SSOHandler getSSOHandler() {
		return ssoHandler;
	}
	
	/**
	 * 验证是否已经单点登录（jsonp）
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	public void authentication(HttpServletRequest request, HttpServletResponse response,FilterChain chain) throws IOException, ServletException {
		String service = request.getParameter("service");
		String callback = request.getParameter("callback");
		String projectCode = request.getParameter("projectCode");
		String gtCookie = this.getSSOCookie(request, response);
		GrantingTicket gt = TicketCache.getGrantingTicket(gtCookie);
		
		System.out.println("===================sso authentication begin(jsonp)========================");
		System.out.println("service="+service);
		System.out.println("projectCode="+projectCode);
		System.out.println("gtCookie="+gtCookie);
		System.out.println("===================sso authentication end(jsonp)========================");
		
		if(null == gtCookie || null ==gt)
		{
			responseJsonp(response,callback,SSOIdentity.error(SSOConstants.SSO_VERIFICATION_MSG00));
			return;
		}
		ProjectEntity p = ProjectCache.getByCode(projectCode);
		
		if(null == projectCode || null ==p)
		{
			
			responseJsonp(response,callback,SSOIdentity.error(SSOConstants.SSO_VERIFICATION_MSG3));
			return;
		}
		
		//生成ticket
		ServiceTicket st = GrantingTicket.generateServiceTicket(service);
		st.setProjectCode(projectCode);
		gt.putServiceTicket(st);
		
		TicketCache.putGrantingTicket(gt);
		TicketCache.putServiceTicket2GrantingTicket(st.getId(), gt.getId());
		
		//返回用户
		User user = gt.getUser();
		responseJsonp(response,callback,SSOIdentity.success(user));
		
	}
	
	
	/**
	 * 单点登录(jsonp)
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	public void signin(HttpServletRequest request, HttpServletResponse response,FilterChain chain) throws IOException, ServletException {
		response.setContentType("text/xml;charset=utf-8");
		response.setCharacterEncoding("utf-8");
		
		String service = request.getParameter("service");
		String identity = request.getParameter("identity");
		String projectCode = request.getParameter("projectCode");
		String password = request.getParameter("password");
		String callback = request.getParameter("callback");
		
		//jsonp传来的没有加密
		password = EncryptUtils.MD5Encode(password);
		//用户验证
		UserAuthService userAuthentication = (UserAuthService)SpringBeanLoader.getBean("userAuthServiceImpl");
		SSOIdentity ssoId = userAuthentication.verificationUser(identity, password);
		
		//如果登陆成功
		if(ssoId.getType().equals(XJJConstants.MSG_TYPE_SUCCESS))
	    {
			 GrantingTicket gt = GrantingTicket.generateGrantingTicket(ssoId.getUser());
			 ServiceTicket st = GrantingTicket.generateServiceTicket(service);
			 st.setProjectCode(projectCode);
			 gt.putServiceTicket(st);
			 
			 TicketCache.putGrantingTicket(gt);
			 TicketCache.putServiceTicket2GrantingTicket(st.getId(), gt.getId());
			 
			 writeCookie(response,gt.getId());
	    }
		
		
	    String jsonUser = JsonUtil.toJSONString(ssoId.getUser()); 
		
		StringBuilder jsonpCallback = new StringBuilder();
		jsonpCallback.append(callback);
		jsonpCallback.append("('");
		if(!"null".equals(jsonUser))
		{
			jsonpCallback.append(jsonUser);
		}
		jsonpCallback.append("');");
		System.out.println("jsonp callback==="+jsonpCallback.toString());
		response.getWriter().print(jsonpCallback.toString());
		
		 
	}
	
	/**
	 * 单点退出
	 * @param request
	 * @param response
	 * @param chain
	 * @throws IOException
	 * @throws ServletException
	 */
	public void signout(HttpServletRequest request, HttpServletResponse response,FilterChain chain) throws IOException, ServletException {
		
		String projectCode = request.getParameter("projectCode");
		String callback = request.getParameter("callback");

		String gtCookie = getSSOCookie(request, response);
		GrantingTicket gt = TicketCache.getGrantingTicket(gtCookie);
		
		if(null == gtCookie || null ==gt)
		{
			responseJsonp(response,callback,SSOIdentity.error(SSOConstants.SSO_VERIFICATION_MSG00));
			return;
		}
		ProjectEntity p = ProjectCache.getByCode(projectCode);
		if(null == projectCode || null ==p)
		{
			responseJsonp(response,callback,SSOIdentity.error(SSOConstants.SSO_VERIFICATION_MSG3));
			return;
		}
		
		//单点退出
		if(SSOUtils.isNotBlank(gtCookie))
		{
			ssoLogout(request,response,gtCookie);
		}
		responseJsonp(response,callback,SSOIdentity.success(SSOConstants.SSO_VERIFICATION_MSG90));
		return;
	}
	
	/**
	 * 验证ticket
	 * @param request
	 * @param response
	 * @param chain
	 * @throws IOException
	 * @throws ServletException
	 */
	public void validateTicket(HttpServletRequest request, HttpServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		String ticket =  request.getParameter("ticket");
		String service =  request.getParameter("service");
		
		String gTicket = TicketCache.getGTicket(ticket);
		GrantingTicket gt = TicketCache.getGrantingTicket(gTicket);
		
		System.out.println("===================sso validateTicket ticket ==="+ticket);
		System.out.println("===================sso validateTicket service ==="+service);
		System.out.println("===================sso validateTicket gTicket ==="+gTicket);
		System.out.println("===================sso validateTicket gt ==="+gt);
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		response.setHeader("Content-type", "text/html;charset=UTF-8"); 
		
		if(null == gTicket || null == gt)
		{
			response.getOutputStream().print("");
			return;
		}
		
		ServiceTicket st = gt.getServiceTicket(ticket, service);
		if(null != st)
		{
			System.out.println("===================sso validateTicket st ==="+st.toString());
			//使ticket失效
			TicketCache.expiredServiceTicket(st.getId());
			
			User user = gt.getUser();
			String json = JsonUtil.toJSONString(user);
			response.getOutputStream().write(json.getBytes("UTF-8"));
			System.out.println("===================sso validateTicket json ==="+json);
			return;
		}else
		{
			response.getOutputStream().print("");
		}
	}
}